package com.example.shutdown;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import android.os.BatteryManager;
import android.os.Bundle;
import android.preference.Preference;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Instrumentation;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		SharedPreferences prefs = getSharedPreferences("com.example.shutdown",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		if (!prefs.getBoolean("firstRun", false)) {	//第一次启动时拷贝关机程序文件，以后不再拷贝
			String apppath = getApplicationContext().getFilesDir().getParent();
			apppath += "/lib/";
			runShellCommand("busybox cp " + apppath
					+ "libshutdown.so /system/bin/shutdown");
			runShellCommand("chmod 777 /system/bin/shutdown");
			editor.putBoolean("firstRun", true);
			editor.commit();
			
		}
	}
	
	

	public static void runShellCommand(String cmd) {
		try {
			Process exeEcho1 = Runtime.getRuntime().exec("su");
			OutputStream ot = exeEcho1.getOutputStream();
			ot.write(cmd.getBytes());
			ot.flush();
			ot.close();
			
		} catch (IOException e) {
			Log.e("clientMsg", "shell cmd wrong:" + e.toString());
		}
	}
	
	public static String loadFileAsString(String filePath){
	    StringBuffer fileData = new StringBuffer(1000);
	    try {
			BufferedReader reader = new BufferedReader(new FileReader(filePath));
			char[] buf = new char[1024];
			int numRead=0;
			while((numRead=reader.read(buf)) != -1){
			    String readData = String.valueOf(buf, 0, numRead);
			    fileData.append(readData);
			}
			reader.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return fileData.toString();
	}
	

}
